package com.sgb.merchant.view.activity;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.CountDownTimer;
import android.text.Html;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.util.Pair;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.im.immodel.IMUtils;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.LoginEvents;
import com.sgb.link.entity.merchant.EnrolInfoEntiy;
import com.sgb.link.entity.merchant.InvestmentDetailEntity;
import com.sgb.link.router.PathLogin;
import com.sgb.link.router.PathMerchant;
import com.sgb.link.router.PathUser;
import com.sgb.link.view.widget.CustomXTabLayout;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantActivityInverstmentDetailBinding;
import com.sgb.merchant.view.adapter.InvestmentDetailAdapter;
import com.sgb.merchant.viewmodel.InvestmentDetailViewModel;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.base.model.entity.SingleItemConstant;
import com.swgk.core.base.model.entity.SingleItemEntity;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


/**
 * @author: 王彬臣
 * @date: 2021/7/13
 * @Description: 投资项目详情页
 */
@Route(path = PathMerchant.InvestmentDetailActivity)
public class InvestmentDetailActivity extends BaseActivity<InvestmentDetailViewModel, MerchantActivityInverstmentDetailBinding> {
    private String[] titles = {"项目简介", "项目要求", "报名单位"};
    @Autowired(name = RouterKey.NO, desc = "详情no")
    long no;


    InvestmentDetailAdapter mAdapter;
    private List<SingleItemEntity> mList;
    private LinearLayoutManager mLinearLayoutManager;
    InvestmentDetailEntity entity;
    private CountDownTimer mTimer;
    private int lastPosition = -1; //用于判断recyclerView滑动的时候 是不是同一个item的位置
    private int mTabPosition = -1; //点击的tab的position
    private boolean isClickTab=true;
    boolean isFouse;//关注标识
    private int id;//控件id
    private boolean isRecyclerScroll;




    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_inverstment_detail;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(InvestmentDetailViewModel.class);

    }

    @Override
    protected void init() {

        ARouter.getInstance().inject(this);
        mBinding.includeTitle.titleView.setText("投资项目详情");
        mBinding.includeTitle.ivBack.setOnClickListener(v -> {
            finish();
        });
        mBinding.setClick(this);
        for (String title : titles) {
            mBinding.tablayout.addTab(mBinding.tablayout.newTab().setText(title));
        }
        mBinding.setLifecycleOwner(this);
        mLinearLayoutManager = new LinearLayoutManager(this);
        mBinding.rvContent.setLayoutManager(mLinearLayoutManager);
        mList = new ArrayList<>();
        mAdapter = new InvestmentDetailAdapter(mList,this);
        mAdapter.bindToRecyclerView(mBinding.rvContent);
        //取消tab点击效果
        mBinding.tablayout.setTabRippleColor(ColorStateList.valueOf(getResources().getColor(R.color.transparent)));

        initEven();
        ininData();
    }

    private void initEven() {
        mBinding.rvContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //当滑动由recyclerView触发时，isClickTab 置true
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    isClickTab=false;
                }
                return false;
            }
        });
        mBinding.rvContent.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if(isClickTab){
                    return;
                }
                isRecyclerScroll=true;
                    try {
                        int currentPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
                        if (lastPosition != currentPosition) {
                            lastPosition = currentPosition;
                            //要滑动的时候 去判断点击的tab的位置跟recyclerView的可见位置做比较 取最大的 否则tab到不了指定点击的位置
                            currentPosition = Math.max(mTabPosition, currentPosition);
                            mBinding.tablayout.getTabAt(currentPosition).select();
                            mTabPosition = -1;//重置下 不然最大值的话 无法滑动
                        }

                    } catch (Exception e) {

                    }
                isRecyclerScroll=false;

            }
        });
        mBinding.tablayout.addOnTabSelectedListener(new CustomXTabLayout.SimpleSelectedListener(){
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                isClickTab = true;
                mTabPosition = tab.getPosition();
                int position = tab.getPosition();
                tipPosition(position);
            }
        });

    }

    private void initTabLayoutTabOnclick() {
        for (int i = 0; i < mBinding.tablayout.getTabCount(); i++) {
            TabLayout.Tab tab = mBinding.tablayout.getTabAt(i);
            //这里使用到反射，拿到Tab对象后获取Class
            //c.getDeclaredField 获取私有属性。
            //“view”是Tab的私有属性名称，类型是 TabView ，TabLayout私有内部类。
            Class<? extends TabLayout.Tab> tabClass = tab.getClass();
            try {
                Field field = tabClass.getDeclaredField("view");
                field.setAccessible(true);
                final View view = (View) field.get(tab);
                view.setTag(i);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isClickTab = true;
                        int position = (int) view.getTag();
                        tipPosition(position);

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //滑动到指定位置
    private void tipPosition(int position) {


        scrollToTop();
     /*   if (position == 2) {*/
        if (!isRecyclerScroll) {
            LinearLayoutManager mLayoutManager = (LinearLayoutManager) mBinding.rvContent.getLayoutManager();
            if (mLayoutManager != null) {
                mLayoutManager.scrollToPositionWithOffset(position, position);
            }
        }
/*
        } else {
            mBinding.rvContent.smoothScrollToPosition(position);
        }*/
    }

    private void ininData() {
        DialogHelper.showProgressDialog(this, "加载中").setCanceledOnTouchOutside(true);
        mViewModel.getDetils(no);
        mViewModel.ldData.observe(this, data -> {
            try {
                entity = data;
                mList.clear();
                mBinding.coordinator.setVisibility(View.VISIBLE);
                mBinding.bidLayout.setVisibility(View.VISIBLE);
                mBinding.tvTitle.setText(data.getItemName());
                mBinding.tvName.setText(data.getCompanyName());
                mBinding.tvPerson.setText(data.getLinkName());
                mBinding.tvPhone.setText(TextUtils.isEmpty(data.getLinkPhone())?"/":data.getLinkPhone());
                if (!TextUtils.isEmpty(data.getFollowNo())) {
                    isFouse = true;
                    mBinding.imageUserFocus.setImageResource(R.mipmap.merchant_icon_yiguanzhu);
                    mBinding.tvUserFocus.setText("已关注");
                    mBinding.tvUserFocus.setTextColor(getResources().getColor(R.color.color_secondary_red));
                }
                if (data.getButtonStatus() != null) {
                    if (data.getButtonStatus().getConstantKey().equals("bt2")) {//已报名
                        mBinding.tvCommit.setText("我已报名");
                        mBinding.tvCommit.setEnabled(false);
                        mBinding.tvCommit.setAlpha(0.5f);
                    } else {
                        mBinding.tvCommit.setText("我要报名");
                        mBinding.tvCommit.setEnabled(true);
                        mBinding.tvCommit.setAlpha(1f);
                    }
                }

                List<String> pics = new ArrayList<>();
                if(data.getImages()!=null) {
                    for (InvestmentDetailEntity.ImagesBean pic : data.getImages()) {
                        pics.add(pic.getImageUrl());
                    }
                }
                mList.add(new SingleItemEntity(SingleItemConstant.TYPE_ONE, data, pics));
                mList.add(new SingleItemEntity<InvestmentDetailEntity>(SingleItemConstant.TYPE_TWO, data));
                mAdapter.notifyDataSetChanged();
                mViewModel.getEnrolList(no);
            }catch (Exception e){

            }

        });
        mViewModel.ldList.observe(this, data -> {
            mList.add(new SingleItemEntity<EnrolInfoEntiy>(SingleItemConstant.TYPE_THREE, data));
            mAdapter.notifyDataSetChanged();
        });
        mAdapter.setToMoreClick(new InvestmentDetailAdapter.toMoreClick() {
            @Override
            public void toMore() {
                ActivityJump.startActivity(PathMerchant.EnrolListActivity, Pair.create(RouterKey.NO, no));
            }
        });
        mViewModel.ldResult.observe(this, result -> {
            if (result.isSuccess()) {
                if (isFouse) {//已关注取消关注
                    isFouse = false;
                    mBinding.imageUserFocus.setImageResource(R.mipmap.merchant_icon_guanzhu);
                    mBinding.tvUserFocus.setText("关注");
                    mBinding.tvUserFocus.setTextColor(getResources().getColor(R.color.color_666666));
                } else {
                    isFouse = true;
                    mBinding.imageUserFocus.setImageResource(R.mipmap.merchant_icon_yiguanzhu);
                    mBinding.tvUserFocus.setText("已关注");
                    mBinding.tvUserFocus.setTextColor(getResources().getColor(R.color.color_secondary_red));
                }
            }
        });
        mViewModel.ldUserInfo.observe(this, userInfo -> {
            String userNo=SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.USER_NO,"");//当前用户no
            if (!TextUtils.isEmpty(userInfo.getImAccount())) {
                if(!userNo.equals(userInfo.getNo())) {
                    IMUtils.getInstance().buildSingleTalking(userInfo.getImAccount());
                }else{
                    MToast.showToast(this, "自己不能咨询自己发布的数据");
                }
            } else {
                MToast.showToast(this, "未获取到用户IM账号");
            }
        });
        mViewModel.ldState.observe(this,state->{
            switch (state){//0未上架 1已删除 2正常
                case -1:
                    mBinding.coordinator.setVisibility(View.GONE);
                    mBinding.bidLayout.setVisibility(View.GONE);
                    mBinding.rlError.setVisibility(View.VISIBLE);
                    mBinding.noDataTv.setText("暂无数据");
                    break;
                case 0:
                    mBinding.coordinator.setVisibility(View.GONE);
                    mBinding.bidLayout.setVisibility(View.GONE);
                    mBinding.rlError.setVisibility(View.VISIBLE);
                    mBinding.noDataTv.setText(Html.fromHtml("当前数据已下架，请<u><font color='#5892FD'>返回列表</font></u>继续浏览吧~"));
                    mBinding.noDataTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
                    break;
                case 1:
                    mBinding.coordinator.setVisibility(View.GONE);
                    mBinding.bidLayout.setVisibility(View.GONE);
                    mBinding.rlError.setVisibility(View.VISIBLE);
                    mBinding.noDataTv.setText(Html.fromHtml("当前数据已删除，请<u><font color='#5892FD'>返回列表</font></u>继续浏览吧~"));
                    mBinding.noDataTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
                    break;
                case 2:
                    mBinding.coordinator.setVisibility(View.VISIBLE);
                    mBinding.bidLayout.setVisibility(View.VISIBLE);
                    mBinding.rlError.setVisibility(View.GONE);
                    clickEvent();

                    break;
            }
        });
    }

    public void countTime(long times, boolean isStart) {
        long dif = times - System.currentTimeMillis();
        mTimer = new CountDownTimer(dif, 1000) {
            public void onTick(long millisUntilFinished) {
                if (!isFinishing()) {
                    if (isStart) {
                        mBinding.tvTimes.setText("报名开始倒计时：" + DateUtils.dateDiff(DateUtils.stampToDay6(times)));
                    } else {
                        mBinding.tvTimes.setText("报名结束倒计时：" + DateUtils.dateDiff(DateUtils.stampToDay6(times)));
                    }
                }

            }

            public void onFinish() {
                if (!isFinishing()) {
                    mViewModel.getDetils(no);

                }
            }
        };
        mTimer.start();
    }

    public void scrollToTop() {
        //拿到 appbar 的 behavior,让 appbar 滚动
        ViewGroup.LayoutParams layoutParams = mBinding.appBarLayout.getLayoutParams();
        CoordinatorLayout.Behavior behavior =
                ((CoordinatorLayout.LayoutParams) layoutParams).getBehavior();
        if (behavior instanceof AppBarLayout.Behavior) {
            AppBarLayout.Behavior appBarLayoutBehavior = (AppBarLayout.Behavior) behavior;
            //拿到下方tabs的y坐标，即为我要的偏移量
            float y = mBinding.tablayout.getY();
            //注意传递负值
            appBarLayoutBehavior.setTopAndBottomOffset((int) -y);
        }

    }

    @Override
    public void onClick(View v) {
        id = v.getId();
        DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(true);
        mViewModel.getState(no);


    }

    private void clickEvent() {
        if (id == R.id.ll_report || id == R.id.ll_inquire_by_letter) {
            MToast.showToast(this, "功能开发中，敬请期待");
        } else if (id == R.id.ll_contact_service) {
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                ActivityJump.startActivity(PathLogin.VerificationCodeLoginActivity);
                return;
            }
            DialogHelper.showProgressDialog(this, "加载中").setCanceledOnTouchOutside(true);
            mViewModel.getImInfo(entity.getCreateUser());

        } else if (id == R.id.line_user_focus) {
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                ActivityJump.startActivity(PathLogin.VerificationCodeLoginActivity);
                return;
            }
            boolean personAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
            if (!personAuth) {//去实名
                new RoundDialog.Builder(this)
                        .title("温馨提示")
                        .content("请先进行实名认证")
                        .cancel("我知道了")
                        .confirm("去认证")
                        .cancelable(false)
                        .confirmCallback(v12 -> ARouter.getInstance().build(PathUser.CertificationActivity).withString("type", "1").navigation()).show();
                return;
            }
            DialogHelper.showProgressDialog(this, "加载中").setCanceledOnTouchOutside(true);
            mViewModel.follow(no);

        } else if (id == R.id.tv_commit) {
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                ActivityJump.startActivity(PathLogin.VerificationCodeLoginActivity);
                return;
            }
            boolean personAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
            if (!personAuth) {//去实名
                new RoundDialog.Builder(this)
                        .title("温馨提示")
                        .content("请先进行实名认证")
                        .cancel("我知道了")
                        .confirm("去认证")
                        .cancelable(false)
                        .confirmCallback(v12 -> ARouter.getInstance().build(PathUser.CertificationActivity).withString("type", "1").navigation()).show();
                return;
            }
            String userNO=SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.USER_NO,"");
            String company= SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NAME, "");
            if(userNO.equals(entity.getCreateUser())&&company.equals(entity.getCompanyName())){
                MToast.showToast(InvestmentDetailActivity.this,"无法报名自己的项目");
                return;
            }
            ARouter.getInstance().build(PathMerchant.InvestmentApplyActivity).withSerializable(RouterKey.DATA,entity).navigation(this,100);
        } else if (id == R.id.iv_map) {
            InvestmentDetailEntity entity = mViewModel.ldData.getValue();
            if (entity != null) {
                ARouter.getInstance().build(PathUser.MapPositionActivity)
                        .withDouble("latitude", Double.valueOf(entity.getLat()))
                        .withDouble("longitude", Double.valueOf(entity.getLng()))
                        .withString("companyName", entity.getCompanyName())
                        .withString("address", entity.getProviceName() + entity.getCityName() + entity.getRegionName() + entity.getAddressInfo())
                        .navigation();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }

    }

    @Override
    public boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LoginEvents event) {
        if (event == null) return;
        if (event.getMessageTag() == EventConstant.EVENT_LOGIN) {
            DialogHelper.showProgressDialog(this, "加载中").setCanceledOnTouchOutside(true);
            if(no!=0)
            mViewModel.getDetils(no);
        }
        EventBus.getDefault().removeStickyEvent(event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            finish();
        }else if(resultCode==200){
            entity.getButtonStatus().setConstantKey("bt2");
            mBinding.tvCommit.setText("我已报名");
            mBinding.tvCommit.setEnabled(false);
            mBinding.tvCommit.setAlpha(0.5f);
        }
    }
}
